//
//  SportModel.m
//  GetFit3.0
//
//  Created by zorro on 2017/7/21.
//  Copyright © 2017年 lxc. All rights reserved.
//

#import "SportModel.h"


// http://apidoc.sty028.com/#api-sportsleep-uploadGfUserSport
// PHP http://119.23.8.182:8081/doc/
// http://119.23.8.182:8082/appversion/index

@implementation SportModel

- (instancetype)init {
    self = [super init];
    if (self) {
        _user_id      = SN_USER.user_id;
        _dateString   = [[NSDate date] dateToDayString];
        _step         = 0;
        _distance     = 0;
        _realDistance = 0;
        _calory       = 0;
        _isFood       = NO;
        NSString *dateY = [[[NSDate date] dateAfterDay:-1] dateToDayString];
        NSString *dateT = [[[NSDate date] dateAfterDay:0] dateToDayString];
        _stepTarget     = SN_USER.target_step;
        _stepquality    = NO;
        _stepBoolFinish = 0;
        
        NSMutableArray *stepArr     = [NSMutableArray array];
        NSMutableArray *distanceArr = [NSMutableArray array];
        NSMutableArray *calArr      = [NSMutableArray array];
        for (int i = 0; i < 48; i++) {
            [stepArr addObject:StrByInt(0)];
            [distanceArr addObject:StrByInt(0)];
            [calArr addObject:StrByInt(0)];
        }
        _stepArray     = [NSArray arrayWithArray:stepArr];
        _distanceArray = [NSArray arrayWithArray:distanceArr];
        _calorArray    = [NSArray arrayWithArray:calArr];
        _stepFinish    = 1;
        _mac = KK_BLEModel.bleMAC;
    }
    
    return self;
}

+ (SportModel *)initWithDate:(NSDate *)date {
    SportModel *model = [[SportModel alloc] init];
    
    model.dateString = [date dateToDayString];
    model.user_id    = SN_USER.user_id;
    model.step       = 0;
    model.distance   = 0;
    model.calory     = 0;
    NSString *dateY = [[[NSDate date] dateAfterDay:-1] dateToDayString];
    NSString *dateT = [[[NSDate date] dateAfterDay:0] dateToDayString];
    model.stepTarget     = SN_USER.target_step;
    model.stepquality    = NO;
    model.isFood         = 0;
    model.stepBoolFinish = 0;
    model.weekCount      = date.weekOfYear;
    model.monthCount     = date.month;
    model.yearCount      = date.year;
    
    NSMutableArray *stepArr     = [NSMutableArray array];
    NSMutableArray *distanceArr = [NSMutableArray array];
    NSMutableArray *calArr      = [NSMutableArray array];
    for (int i = 0; i < 48; i++) {
        [stepArr addObject:StrByInt(0)];
        [distanceArr addObject:StrByInt(0)];
        [calArr addObject:StrByInt(0)];
    }
    model.stepArray     = [NSArray arrayWithArray:stepArr];
    model.distanceArray = [NSArray arrayWithArray:distanceArr];
    model.calorArray    = [NSArray arrayWithArray:calArr];
    model.stepFinish    = 1;
    model.mac = KK_BLEModel.bleMAC;
    return model;
}

- (void)updateToDBSafely {
    NSString *where = [NSString stringWithFormat:@"user_id = '%@' and dateString = '%@'",
                       SN_USER.user_id, self.dateString];
    SportModel *model = [SportModel searchSingleWithWhere:where orderBy:nil];
    
    if (model) {
        [SportModel updateToDB:self where:nil];
    }
}

+ (SportModel *)getSportModelFromDB {
    SportModel *model = [SportModel getSportModelFromDBWith:[NSDate date]];
    return model;
}

+ (SportModel *)getSportModelFromDBWithDayString:(NSString *)string {
    NSString *where = [NSString stringWithFormat:@"user_id = '%@' and dateString = '%@'",
                       SN_USER.user_id, string];
    SportModel *model = [SportModel searchSingleWithWhere:where orderBy:nil];
    model.realDistance = SN_USER.isMetricSystem?model.distance * 0.6213712:model.distance;
    if (!model) {
        model            = [[SportModel alloc] init];
        model.dateString = string;
        model.mac = KK_BLEModel.bleMAC;
        NSDate *ddd = [NSDate dateByString:string];
        model.weekCount  = ddd.weekOfYear;
        model.monthCount = ddd.month;
        model.yearCount  = ddd.year;
        model.user_id    = SN_USER.user_id;
        model.stepFinish = 1;
        model.stepquality = NO;
        model.isFood = NO;
    }
    return model;
}

+ (SportModel *)getSportModelFromDBWith:(NSDate *)date {
    NSString *where = [NSString stringWithFormat:@"user_id = '%@' and dateString = '%@'",
                       SN_USER.user_id, [date dateToDayString]];
    SportModel *model = [SportModel searchSingleWithWhere:where orderBy:nil];
    model.realDistance = SN_USER.isMetricSystem?model.distance * 0.6213712:model.distance;
    if (!model) {
        model = [SportModel pedometerSaveEmptyModelToDBWithDate:date isSaveAllDay:NO];
    }
    model.stepFinish = 1;
    return model;
}

+ (SportModel *)pedometerSaveEmptyModelToDBWithDate:(NSDate *)date isSaveAllDay:(BOOL)save {
    SportModel *model = [SportModel initWithDate:date];
    [SportModel creatEmptyDataArrayWithModel:model];
    if (![date compareWithDate:[NSDate date]] &&
        [date timeIntervalSince1970] < [[NSDate date] timeIntervalSince1970]) {
        // NSLog(@"model.isSaveAllDay = ..%@", date);
        if (save) {
            model.isSaveAllDay = YES;
        }
    }
    [model saveToDB];
    
    return model;
}

// 为模型创建空值的对象
+ (void)creatEmptyDataArrayWithModel:(SportModel *)model {
}

// 表名
+ (NSString *)getTableName {
    return @"SportModel";
}

// 复合主键
+ (NSArray *)getPrimaryKeyUnionArray {
    return @[@"user_id", @"dateString"];
}

// 表版本
+ (int)getTableVersion {
    return 1;
}

+ (void)initialize {
    [super initialize];
    
    [self bindYYJSONKey:@"stepDuration" toProperty:@"stepDuration"];
    [self bindYYJSONKey:@"target_step" toProperty:@"stepTarget"];
    [self bindYYJSONKey:@"data" toProperty:@"detailData"];
    [self bindYYJSONKey:@"date" toProperty:@"dateString"];
    
    [self removePropertyWithColumnName:@"detailData"];
}

- (void)updateRealStepData:(NSData *)data {
    UInt8 val[20] = {0};
    
    [data getBytes:&val length:data.length];
    NSString  *content    = [NSString stringWithFormat:@"%@", data];
    NSInteger tmpStep     = 0;
    NSInteger tmpDistance = 0;
    NSInteger tmpCalory   = 0;
    NSInteger tmpDuration = 0;
    tmpStep     = val[3] * 256 * 256 * 256 + val[4] * 256 * 256 + val[5] * 256 + val[6];
    NSLog(@"tmpStep:%ld",tmpStep);
    tmpDistance = val[7] * 256 * 256 * 256 + val[8] * 256 * 256 + val[9] * 256 + val[10];
    tmpCalory   = val[11] * 256 * 256 * 256 + val[12] * 256 * 256 + val[13] * 256 + val[14];
    tmpDuration = val[15] * 256 + val[16];
    
    SportModel *model = SN_PublicClass.todaySport;
    model.step = tmpStep;
    if (SN_USER.isMetricSystem) {
        model.distance = tmpDistance * 1.609344;
    } else {
        model.distance = tmpDistance;
    }
    model.realDistance = tmpDistance;
    model.calory       = tmpCalory;
    model.stepDuration = tmpDuration;
    if (model.step > model.stepTarget) {
        model.stepquality    = YES;
        model.stepBoolFinish = 1;
    } else {
        model.stepquality    = NO;
        model.stepBoolFinish = 0;
    }
    LogWrite(@"实时运动", content, nil);
    
    NSInteger      currentMinIndex = [NSDate getCurrentMinTotal]/30;
    NSInteger      lastStep        = 0;
    NSMutableArray *newStepArray   = [[NSMutableArray alloc] init];
    for (NSString *step in model.stepArray) {
        lastStep += step.integerValue;
        [newStepArray addObject:step];
    }

    NSString  *lastIndexStep = [model.stepArray objectAtIndex:currentMinIndex];
    NSInteger replaceStep    = 0;
    if (model.step > lastStep) {
        replaceStep = lastIndexStep.integerValue + model.step - lastStep;
        [newStepArray replaceObjectAtIndex:currentMinIndex withObject:StrByInt(replaceStep)];
        model.stepArray = [NSArray arrayWithArray:newStepArray];
    }
    
    NSLog(@"实时步数 当前时间下标>>>%d  最后的总步数>>>%d 实时步数%d 误差步数>>>%d", currentMinIndex, lastStep, model.step, model.step - lastStep);
    
    // 日志
    NSString *modelStepStr = [NSString stringWithFormat:@"%ld",model.step];
    LogWrite(@"实时步数值", modelStepStr, nil);
    
    [model updateToDB];
}

// 步数大数据
+ (void)updateSportData:(NSData *)sportData {
    UInt8 val[20] = {0};
    
    [sportData getBytes:&val length:sportData.length];
    NSString *content = [NSString stringWithFormat:@"%@", sportData];
    // 开始
    if (val[3] == 0 || val[3] == 6) {
        [SN_PublicClass.stepArray removeAllObjects];
        SN_PublicClass.sportTotal = 0;
        for (int i = 0; i < 48; i++) {
            [SN_PublicClass.stepArray addObject:@"0"];
        }
    }
    //防止手环过来的数据漏发val[3] == 0或val[3] == 6这条导致数组为空
    if (SN_PublicClass.stepArray.count==0) {
        for (int i = 0; i < 48; i++) {
            [SN_PublicClass.stepArray addObject:@"0"];
        }
    }
    if (val[2] == 3) {
        if (val[3] == 0) {
            LogWrite(@"今日步数大数据", content, nil);
        } else if (val[3] == 6) {
            LogWrite(@"昨日步数大数据", content, nil);
        } else {
            LogWrite(nil, content, nil);
        }
    } else if (val[2] == 5) {
        if (val[3] == 0) {
            LogWrite(@"今日距离大数据", content, nil);
        } else if (val[3] == 6) {
            LogWrite(@"昨日距离大数据", content, nil);
        } else {
            LogWrite(nil, content, nil);
        }
    } else {
        if (val[3] == 0) {
            LogWrite(@"今日卡路里大数据", content, nil);
        } else if (val[3] == 6) {
            LogWrite(@"昨日卡路里大数据", content, nil);
        } else {
            LogWrite(nil, content, nil);
        }
    }
    for (int i = 4; i < 19; i += 2) {
        if (val[3] >= 0 && val[3] <= 11) {
            NSInteger number   = val[i] * 256 + val[i + 1];
            int       indexRow = val[3];
            if (val[3] > 5) {
                indexRow = val[3] - 6;
            }
            int index = indexRow * 8 + (i - 4)/2;
            if(number >=10000)
            {
                number = 0;
            }
            [SN_PublicClass.stepArray replaceObjectAtIndex:index withObject:StrByInt(number)];
             SN_PublicClass.sportTotal += number;
        }
    }
    SportModel *model;
    if (val[3] == 5) {
        model = SN_PublicClass.todaySport;
        [model updateSportDataWithType:val[2] with:YES];
        [model updateToDB];
    } else if (val[3] == 11) {
        model = SN_PublicClass.yesSport;
        [model updateSportDataWithType:val[2] with:NO];
        [model updateToDB];
    }
}

- (void)updateTodaySportData:(NSInteger)type
{
    if (type == 3) {
        [self updateTodaySport];
    }
    if (type == 5) {
        [self updateTodayDistance];
    }
    if (type == 6) {
        [self updateTodayCalor];
    }
}

// 今天步数 距离 卡路里
- (void)updateTodaySport
{
    NSInteger step = SN_PublicClass.sportTotal;
    NSArray *stepArray = [NSArray arrayWithArray:SN_PublicClass.stepArray];
    
    NSString *dateStr = [[[NSDate date] dateAfterDay:0] dateToDayString];
    SportModel *model = [SportModel getSportModelFromDBWithDayString:dateStr];
    model.step = step;
    model.stepArray = [NSArray arrayWithArray:stepArray];
    model.mac = KK_BLEModel.bleMAC;
    if (model.step >= _stepTarget) {//测试
        model.stepquality    = YES;
        model.stepBoolFinish = 1;
    } else {
        model.stepquality    = NO;
        model.stepBoolFinish = 0;
    }
    
    if (step >150000) {
        model.step = 0;
        LogWrite(@"同步今天步数异常🙂🙂🙂150000",nil, nil);
    }
    
    [model updateToDB];
    SN_PublicClass.todaySport = model;
}

- (void)updateTodayDistance
{
    NSInteger distance = SN_PublicClass.sportTotal;
    NSArray *distanceArray = [NSArray arrayWithArray:SN_PublicClass.stepArray];
    
    NSString *dateStr = [[[NSDate date] dateAfterDay:0] dateToDayString];
    SportModel *model = [SportModel getSportModelFromDBWithDayString:dateStr];
    model.distance = distance;
    if (SN_USER.isMetricSystem) {
        model.realDistance = SN_PublicClass.sportTotal *0.6213712;
    } else {
        model.realDistance = SN_PublicClass.sportTotal;
    }
    model.distanceArray = [NSArray arrayWithArray:distanceArray];
    model.mac = KK_BLEModel.bleMAC;
    [model updateToDB];
    SN_PublicClass.todaySport = model;
}

- (void)updateTodayCalor
{
    NSInteger calory = SN_PublicClass.sportTotal;
    NSArray *calorArray = [NSArray arrayWithArray:SN_PublicClass.stepArray];
    
    NSString *dateStr = [[[NSDate date] dateAfterDay:0] dateToDayString];
    SportModel *model = [SportModel getSportModelFromDBWithDayString:dateStr];
    model.calory = calory;
    model.calorArray = [NSArray arrayWithArray:calorArray];
    model.mac = KK_BLEModel.bleMAC;
    [model updateToDB];
    SN_PublicClass.todaySport = model;
}

// 昨天步数 距离 卡路里
- (void)updateYesSportData:(NSInteger)type
{
    if (type == 3) {
        [self updateYesSport];
    }
    if (type == 5) {
        [self updateYesDistance];
    }
    if (type == 6) {
        [self updateYesCalor];
    }
}

- (void)updateYesSport
{
    NSString *macWhere = [NSString stringWithFormat:@"select mac from SportModel where user_id = '%@' and dateString = '%@'", SN_USER.user_id,[[NSDate date] dateAfterDay:-1].dateToDayString];
    NSString *yesMac = [[SportModel getUsingLKDBHelper]executeScalarWithSQL:macWhere arguments:nil];
    NSString *s1 = [yesMac lowercaseString];
    NSString *s2 = [KK_BLEModel.bleMAC lowercaseString];
    NSLog(@"之前的手环>>>>>%@",s1);
    NSLog(@"现在的手环>>>>>%@",s2);
    
    NSString *dateStr = [[[NSDate date] dateAfterDay:-1] dateToDayString];
    SportModel *model = [SportModel getSportModelFromDBWithDayString:dateStr];
    
    NSMutableArray *yesArray = [NSMutableArray array];
    NSArray *array = [NSArray arrayWithArray:SN_PublicClass.stepArray];
    
    //同一个手环覆盖
    if ([s1 isEqualToString:s2]) {
        yesArray = [NSMutableArray arrayWithArray:model.stepArray];
        for (int k = 0; k<yesArray.count; k++) {
            int steps = [[array objectAtIndex:k] intValue];
            if (steps > 0) {
                [yesArray replaceObjectAtIndex:k withObject:StrByInt(steps)];
            }
        }
        NSInteger step = [[yesArray valueForKeyPath:@"@sum.floatValue"] integerValue];
        model.step = step;
        model.mac = s1;
    }
    else
    //不同手环不做覆盖
    {
        model.mac = s1;
        yesArray = [NSMutableArray arrayWithArray:model.stepArray];
    }
    
    if ([s1 isEqualToString:@""]) {
        yesArray = [NSMutableArray arrayWithArray:array];
        NSInteger step = [[yesArray valueForKeyPath:@"@sum.floatValue"] integerValue];
        model.step = step;
        model.mac = s2;
    }

    model.stepArray = [NSArray arrayWithArray:yesArray];
    if (model.step >= model.stepTarget) {//测试
        model.stepquality    = YES;
        model.stepBoolFinish = 1;
    } else {
        model.stepquality    = NO;
        model.stepBoolFinish = 0;
    }
    [model updateToDB];
    SN_PublicClass.yesSport = model;
}

- (void)updateYesDistance
{
    NSString *macWhere = [NSString stringWithFormat:@"select mac from SportModel where user_id = '%@' and dateString = '%@'", SN_USER.user_id,[[NSDate date] dateAfterDay:-1].dateToDayString];
    NSString *yesMac = [[SportModel getUsingLKDBHelper]executeScalarWithSQL:macWhere arguments:nil];
    NSString *s1 = [yesMac lowercaseString];
    NSString *s2 = [KK_BLEModel.bleMAC lowercaseString];
//    NSLog(@"之前的手环>>>>>%@",s1);
//    NSLog(@"现在的手环>>>>>%@",s2);
    
    NSString *dateStr = [[[NSDate date] dateAfterDay:-1] dateToDayString];
    SportModel *model = [SportModel getSportModelFromDBWithDayString:dateStr];
    
    NSMutableArray *yesArray = [NSMutableArray array];
    NSArray *array = [NSArray arrayWithArray:SN_PublicClass.stepArray];
    
    //同一个手环覆盖
    if ([s1 isEqualToString:s2]) {
        yesArray = [NSMutableArray arrayWithArray:model.stepArray];
        for (int k = 0; k<yesArray.count; k++) {
            int distance = [[array objectAtIndex:k] intValue];
            if (distance > 0) {
                [yesArray replaceObjectAtIndex:k withObject:StrByInt(distance)];
            }
        }
        NSInteger distance = [[yesArray valueForKeyPath:@"@sum.floatValue"] integerValue];
        model.distance = distance;
        if (SN_USER.isMetricSystem) {
            model.realDistance = model.distance *0.6213712;
        } else {
            model.realDistance = model.distance;
        }
        model.distanceArray = [NSArray arrayWithArray:yesArray];
        model.mac = s1;
    }
    else
        //不同手环不做覆盖
    {
        model.mac = s1;
        yesArray = [NSMutableArray arrayWithArray:model.distanceArray];
    }
    
    if ([s1 isEqualToString:@""]) {
        yesArray = [NSMutableArray arrayWithArray:array];
        NSInteger distance = [[yesArray valueForKeyPath:@"@sum.floatValue"] integerValue];
        model.distance = distance;
        if (SN_USER.isMetricSystem) {
             model.realDistance = model.distance *0.6213712;
        } else {
             model.realDistance = model.distance;
        }
        model.distanceArray = [NSArray arrayWithArray:yesArray];
        model.mac = s2;
    }
    
    model.distanceArray = [NSArray arrayWithArray:yesArray];
    [model updateToDB];
    SN_PublicClass.yesSport = model;
}

- (void)updateYesCalor
{
    NSString *macWhere = [NSString stringWithFormat:@"select mac from SportModel where user_id = '%@' and dateString = '%@'", SN_USER.user_id,[[NSDate date] dateAfterDay:-1].dateToDayString];
    NSString *yesMac = [[SportModel getUsingLKDBHelper]executeScalarWithSQL:macWhere arguments:nil];
    NSString *s1 = [yesMac lowercaseString];
    NSString *s2 = [KK_BLEModel.bleMAC lowercaseString];
//    NSLog(@"之前的手环>>>>>%@",s1);
//    NSLog(@"现在的手环>>>>>%@",s2);
    
    NSString *dateStr = [[[NSDate date] dateAfterDay:-1] dateToDayString];
    SportModel *model = [SportModel getSportModelFromDBWithDayString:dateStr];
    
    NSMutableArray *yesArray = [NSMutableArray array];
    NSArray *array = [NSArray arrayWithArray:SN_PublicClass.stepArray];
    
    //同一个手环覆盖
    if ([s1 isEqualToString:s2]) {
        yesArray = [NSMutableArray arrayWithArray:model.calorArray];
        for (int k = 0; k<yesArray.count; k++) {
            int calors = [[array objectAtIndex:k] intValue];
            if (calors > 0) {
                [yesArray replaceObjectAtIndex:k withObject:StrByInt(calors)];
            }
        }
        NSInteger calors = [[yesArray valueForKeyPath:@"@sum.floatValue"] integerValue];
        model.calory = calors;
        model.mac = s1;
    }
    else
        //不同手环不做覆盖
    {
        model.mac = s1;
        yesArray = [NSMutableArray arrayWithArray:model.calorArray];
    }
    
    if ([s1 isEqualToString:@""]) {
        yesArray = [NSMutableArray arrayWithArray:array];
        NSInteger calors = [[yesArray valueForKeyPath:@"@sum.floatValue"] integerValue];
        model.calory = calors;
        model.mac = s2;
    }
    
    model.calorArray = [NSArray arrayWithArray:yesArray];
    [model updateToDB];
    SN_PublicClass.yesSport = model;
}

// 分类型保存
- (void)updateSportDataWithType:(NSInteger)type with:(BOOL)today {
    if (today) {
        [self updateTodaySportData:type];
    }
    else
    {
        [self updateYesSportData:type];
    }

    return;
    
    if (type == 3) { // 计步
        //_step = SN_PublicClass.sportTotal;
        _stepArray = [NSArray arrayWithArray:SN_PublicClass.stepArray];
        if (!today) {//昨天的大数据保存时先和数据库的数据做对比后根据情况覆盖后再存到数据库
            NSString *macWhere = [NSString stringWithFormat:@"select mac from SportModel where user_id = '%@' and dateString = '%@'", SN_USER.user_id,[[NSDate date] dateAfterDay:-1].dateToDayString];
            NSString *yesMac = [[SportModel getUsingLKDBHelper]executeScalarWithSQL:macWhere arguments:nil];
            if ([[yesMac uppercaseString] isEqualToString:[KK_BLEModel.bleMAC uppercaseString]]) {//同一手环的数据做合并操作，不同手环的数据直接不处理
                NSString *where = [NSString stringWithFormat:@"user_id = '%@' and dateString = '%@'", SN_USER.user_id,[[NSDate date] dateAfterDay:-1].dateToDayString];
                NSMutableArray *tmpArr = ((SportModel *)[SportModel searchSingleWithWhere:where orderBy:nil]).stepArray.mutableCopy;
                for (int i = 0; i<tmpArr.count; i++) {
                    if ([SN_PublicClass.stepArray[i]intValue] > 0) {
                        [tmpArr replaceObjectAtIndex:i withObject:SN_PublicClass.stepArray[i]];
                    }
                }
                _step = [[tmpArr valueForKeyPath:@"@sum.floatValue"] integerValue];
                _stepArray = [NSArray arrayWithArray:tmpArr];
            }else if ([yesMac isEqualToString:@""]){
                _step = SN_PublicClass.sportTotal;
                _stepArray = [NSArray arrayWithArray:SN_PublicClass.stepArray];
                _mac = KK_BLEModel.bleMAC;
            }
            else{
                NSString *where = [NSString stringWithFormat:@"user_id = '%@' and dateString = '%@'", SN_USER.user_id,[[NSDate date] dateAfterDay:-1].dateToDayString];
                SportModel *model = [SportModel searchSingleWithWhere:where orderBy:nil];
                _step = model.step;
                _stepArray = model.stepArray;
            }
        }
        if (_step >= _stepTarget) {//测试
            _stepquality    = YES;
            _stepBoolFinish = 1;
        } else {
            _stepquality    = NO;
            _stepBoolFinish = 0;
        }
        
        if (today) {
            NSLog(@"今日步数>>>%d",_step);
        }
        else
        {
            NSLog(@"昨日步数>>>%d",_step);
        }
        
    } else if (type == 5) { // 距离
        //_distance = SN_PublicClass.sportTotal;
        //_realDistance = SN_PublicClass.sportTotal;
        _distanceArray = [NSArray arrayWithArray:SN_PublicClass.stepArray];
        if (!today) {
            [self resetYesDataWithString:@"distanceArray"];
            NSString *macWhere = [NSString stringWithFormat:@"select mac from SportModel where user_id = '%@' and dateString = '%@'", SN_USER.user_id,[[NSDate date] dateAfterDay:-1].dateToDayString];
            NSString *yesMac = [[SportModel getUsingLKDBHelper]executeScalarWithSQL:macWhere arguments:nil];
            if ([[yesMac uppercaseString] isEqualToString:[KK_BLEModel.bleMAC uppercaseString]]) {
                NSString *where = [NSString stringWithFormat:@"user_id = '%@' and dateString = '%@'", SN_USER.user_id,[[NSDate date] dateAfterDay:-1].dateToDayString];
                NSMutableArray *tmpArr = ((SportModel *)[SportModel searchSingleWithWhere:where orderBy:nil]).distanceArray.mutableCopy;
                for (int i = 0; i<tmpArr.count; i++) {
                    if ([SN_PublicClass.stepArray[i]intValue] > 0) {
                        [tmpArr replaceObjectAtIndex:i withObject:SN_PublicClass.stepArray[i]];
                    }
                }
                SN_PublicClass.sportTotal = [[tmpArr valueForKeyPath:@"@sum.floatValue"] integerValue];
                _distance = SN_PublicClass.sportTotal;
                if (SN_USER.isMetricSystem) {
                    _realDistance = SN_PublicClass.sportTotal *0.6213712;
                } else {
                    _realDistance = SN_PublicClass.sportTotal;
                }
                _distanceArray = [NSArray arrayWithArray:tmpArr];
            }else if ([yesMac isEqualToString:@""]){
                _distance = SN_PublicClass.sportTotal;
                if (SN_USER.isMetricSystem) {
                    _realDistance = SN_PublicClass.sportTotal *0.6213712;
                } else {
                    _realDistance = SN_PublicClass.sportTotal;
                }
                _distanceArray = [NSArray arrayWithArray:SN_PublicClass.stepArray];
                _mac = KK_BLEModel.bleMAC;
            }
            else{
                NSString *where = [NSString stringWithFormat:@"user_id = '%@' and dateString = '%@'", SN_USER.user_id,[[NSDate date] dateAfterDay:-1].dateToDayString];
                SportModel *model = [SportModel searchSingleWithWhere:where orderBy:nil];
                _distance = model.distance;
                if (SN_USER.isMetricSystem) {
                    _realDistance = model.distance *0.6213712;
                } else {
                    _realDistance = model.distance;
                }
                _distanceArray = model.distanceArray;
            }
        }
    } else if (type == 6) { // 卡路里
        //_calory = SN_PublicClass.sportTotal;
        _calorArray = [NSArray arrayWithArray:SN_PublicClass.stepArray];
        if (today) {
             NSLog(@"卡路里今天>>>>%@",_calorArray);
        }
        else
        {
            NSLog(@"卡路里昨天>>>>%@",_calorArray);
        }
        
        if (!today) {
            NSString *macWhere = [NSString stringWithFormat:@"select mac from SportModel where user_id = '%@' and dateString = '%@'", SN_USER.user_id,[[NSDate date] dateAfterDay:-1].dateToDayString];
            NSString *yesMac = [[SportModel getUsingLKDBHelper]executeScalarWithSQL:macWhere arguments:nil];
            if ([[yesMac uppercaseString] isEqualToString:[KK_BLEModel.bleMAC uppercaseString]]) {
                NSString *where = [NSString stringWithFormat:@"user_id = '%@' and dateString = '%@'", SN_USER.user_id,[[NSDate date] dateAfterDay:-1].dateToDayString];
                NSMutableArray *tmpArr = ((SportModel *)[SportModel searchSingleWithWhere:where orderBy:nil]).calorArray.mutableCopy;
                for (int i = 0; i<tmpArr.count; i++) {
                    if ([SN_PublicClass.stepArray[i]intValue] > 0) {
                        [tmpArr replaceObjectAtIndex:i withObject:SN_PublicClass.stepArray[i]];
                    }
                }
                _calory = [[tmpArr valueForKeyPath:@"@sum.floatValue"] integerValue];
                _calorArray = [NSArray arrayWithArray:tmpArr];
            }else if ([yesMac isEqualToString:@""]){
                _calory = SN_PublicClass.sportTotal;
                _calorArray = [NSArray arrayWithArray:SN_PublicClass.stepArray];
                _mac = KK_BLEModel.bleMAC;
            }
            else{
                NSString *where = [NSString stringWithFormat:@"user_id = '%@' and dateString = '%@'", SN_USER.user_id,[[NSDate date] dateAfterDay:-1].dateToDayString];
                SportModel *model = [SportModel searchSingleWithWhere:where orderBy:nil];
                _calory = model.calory;
                _calorArray = model.calorArray;
            }
        }
    }
}
-(void)resetYesDataWithString:(NSString *)str{
    
}
+ (void)getMaxDayStep {
    NSString *where   = [NSString stringWithFormat:@"select max(step) from SportModel where user_id = '%@' ", SN_USER.user_id];
    NSString *maxStep = [[self getUsingLKDBHelper] executeScalarWithSQL:where arguments:nil];
    
    SN_USER.max_step = maxStep.integerValue;
    NSString *dateWhere   = [NSString stringWithFormat:@"select dateString from SportModel where step = '%@' and user_id = '%@'", maxStep, SN_USER.user_id];
    NSString *maxStepDate = [[self getUsingLKDBHelper] executeScalarWithSQL:dateWhere arguments:nil];
    SN_USER.max_step_date = [maxStepDate stringByReplacingOccurrencesOfString:@"-" withString:@"/"];
}

+ (void)getmaxContinueDays {
    NSString       *where    = [NSString stringWithFormat:@"user_id = '%@'", SN_USER.user_id];
    NSMutableArray *totalArr = [SportModel searchWithWhere:where];
    NSMutableArray *reachArr = [NSMutableArray array];
    
    for (SportModel *model in totalArr) {
        if (model.stepquality && model.stepTarget > 0) {
            [reachArr addObject:model];
        }
    }
    NSMutableArray *continueArr = [NSMutableArray array];
    NSMutableArray *subArr      = [NSMutableArray array];
    SportModel     *tmpModel    = [[SportModel alloc]init];
    for (int i = 0; i < reachArr.count; i++) {
        SportModel *model = reachArr[i];
        if (i == 0) {
            [subArr addObject:model];
            tmpModel = model;
            if (reachArr.count == 1) {
                [continueArr addObject:subArr];
            }
        } else {
            NSDate           *date1     = [NSDate dateByString:tmpModel.dateString];
            NSDate           *date2     = [NSDate dateByString:model.dateString];
            NSCalendar       *gregorian = [NSCalendar currentCalendar];
            unsigned int     unitFlags  = NSCalendarUnitDay;
            NSDateComponents *comps     = [gregorian components:unitFlags fromDate:date1 toDate:date2 options:0];
            if (comps.day == 1) {
                [subArr addObject:model];
                if (i==reachArr.count-1) {
                    [continueArr addObject:subArr];
                }
            } else {
                [continueArr addObject:subArr];
                subArr = [NSMutableArray array];
                [subArr addObject:model];
            }
            tmpModel = model;
        }
    }
    NSArray *result = [continueArr sortedArrayUsingComparator:^NSComparisonResult (id _Nonnull obj1, id _Nonnull obj2) {
        NSMutableArray *arr1 = obj1;
        NSMutableArray *arr2 = obj2;
        return [@(arr1.count) compare:@(arr2.count)];
    }];
    NSArray *maxReachArr = result.lastObject;
    maxReachArr = [maxReachArr sortedArrayUsingComparator:^NSComparisonResult (id _Nonnull obj1, id _Nonnull obj2) {
        SportModel *model1 = obj1;
        SportModel *model2 = obj2;
        return [[NSDate dateByString:model1.dateString] compare:[NSDate dateByString:model2.dateString]];
    }];
    SN_USER.max_reach_times = maxReachArr.count;
    SN_USER.max_reach_start = [((SportModel *)maxReachArr.firstObject).dateString stringByReplacingOccurrencesOfString:@"-" withString:@"/"];
    SN_USER.max_reach_end   = [((SportModel *)maxReachArr.lastObject).dateString stringByReplacingOccurrencesOfString:@"-" withString:@"/"];
}

+ (void)getMaxWeekStep {
    NSDate    *startDate = [[NSDate date] beginningOfWeek];
    NSDate    *endDate   = [[NSDate date] endOfWeek];
    NSInteger maxStep    = 0;
    NSInteger tmpStep    = 0;
    
    for (int i = 0; i < MAXFLOAT; i++) {
        if (i>0) {
            startDate = [startDate dateByAddingWeeks:-1];
            endDate   = [endDate dateByAddingWeeks:-1];
        }
        if ([startDate compare:SN_USER.registerDate] == -1) {
            return;
        } else {
            NSString       *where = [NSString stringWithFormat:@"user_id = '%@' and dateString >= '%@' and dateString <= '%@'", SN_USER.user_id, startDate.dateToDayString, endDate.dateToDayString];
            NSMutableArray *arr   = [SportModel searchColumn:@"step" where:where orderBy:@"dateString" offset:0 count:7];
            tmpStep = [[arr valueForKeyPath:@"@sum.floatValue"] integerValue];
            if (tmpStep > maxStep) {
                maxStep                = tmpStep;
                SN_USER.max_week_step  = maxStep;
                SN_USER.max_week_start = [startDate.dateToDayString stringByReplacingOccurrencesOfString:@"-" withString:@"/"];
                SN_USER.max_week_end   = [endDate.dateToDayString stringByReplacingOccurrencesOfString:@"-" withString:@"/"];
            }
        }
    }
}

+ (void)getMaxMonthStep {
    NSDate    *startDate = [[NSDate date] beginningOfMonth];
    NSDate    *endDate   = [[NSDate date] endOfMonth];
    NSInteger maxStep    = 0;
    NSInteger tmpStep    = 0;
    
    for (int i = 0; i < MAXFLOAT; i++) {
        if (i>0) {
            startDate = [startDate dateByAddingMonths:-1];
            endDate   = [startDate endOfMonth];
        }
        if ([startDate compare:SN_USER.registerDate] == -1) {
            return;
        } else {
            NSString       *where = [NSString stringWithFormat:@"user_id = '%@' and dateString >= '%@' and dateString <= '%@'", SN_USER.user_id, startDate.dateToDayString, endDate.dateToDayString];
            NSMutableArray *arr   = [SportModel searchColumn:@"step" where:where orderBy:@"dateString" offset:0 count:31];
            tmpStep = [[arr valueForKeyPath:@"@sum.floatValue"] integerValue];
            if (tmpStep > maxStep) {
                maxStep                = tmpStep;
                SN_USER.max_month_step = maxStep;
                SN_USER.max_month      = [[startDate.dateToDayString substringToIndex:7] stringByReplacingOccurrencesOfString:@"-" withString:@"/"];
            }
        }
    }
}

+ (void)sportTransEnd {
    NSLog(@"运动数据同步完成>>>");
    
    [SN_Net updateEveryModelWithType:HJUpdateStep];
}

+ (NSInteger)localSportDays {
    NSString *where = [NSString stringWithFormat:@"user_id = '%@' and step > 0", SN_USER.user_id];
    
    return [SportModel rowCountWithWhere:where];
}

// 将数据从服务器同步下来
- (void)saveToDBByDownload {
    NSDate *date = [NSDate dateByString:self.dateString];
    
    self.weekCount  = date.weekOfYear;
    self.monthCount = date.month;
    self.yearCount  = date.year;
    
    NSDictionary *dict = (NSDictionary *)[self.detailData parseJSONString];
    if ([dict isKindOfClass:NSDictionary.class] && dict.allKeys.count > 0) {
        self.stepArray     = [NSArray arrayWithArray:dict[@"step"]];
        self.distanceArray = [NSArray arrayWithArray:dict[@"distance"]];
        self.calorArray    = [NSArray arrayWithArray:dict[@"cal"]];
    }
    
    if (self.stepTarget > 0 && self.stepTarget > 0 && self.step >= self.stepTarget) {
        self.stepquality = YES;
    }
    
    NSString *todayStr = [[NSDate date] dateToDayString];
    if (self.dateString != todayStr) {
        self.isSaveAllDay   = YES;
        self.stepFinish     = YES;
        self.stepBoolFinish = YES;
    }
    [self updateToDB];
}

+ (NSArray *)get30daysData:(int)dateIndex
{
    NSMutableArray *Array = [NSMutableArray array];
    for (int i = dateIndex; i <=0; i++) {
        NSString *lastStr = [[[NSDate date] dateAfterDay:i] dateToDayString];
        SportModel *model = [SportModel getSportModelFromDBWithDayString:lastStr];
        [Array addObject:model];

    }
    return Array;
}

@end

